const buildSubtreeFromLeaves = (trees: any, leafIds: any) => {
    // 创建一个映射，用于快速查找节点
    const nodeMap = new Map();
    trees.forEach((tree: any) => {
        const traverse = (node: any) => {
            nodeMap.set(node._id, { ...node, children: [] });
            if (node.children && node.children.length > 0) {
                node.children.forEach(traverse);
            }
        };
        traverse(tree);
    });

    // 创建一个新的对象来保存新树的节点，并确保每个节点只被添加一次
    const newNodeMap = new Map();

    // 遍历所有叶子节点，添加它们及其祖先到新树中
    leafIds.forEach((leafId: any) => {
        let currentNode = nodeMap.get(leafId);
        while (currentNode && !newNodeMap.has(currentNode._id)) {
            newNodeMap.set(currentNode._id, { ...currentNode });
            currentNode =
                currentNode.parentId !== "0" ? nodeMap.get(currentNode.parentId) : null;
        }

        // 构建从叶子节点到根节点的路径，确保父子关系正确建立
        let pathNode = newNodeMap.get(leafId);
        while (pathNode) {
            if (pathNode.parentId === "0") {
                break;
            }
            const parentNode = newNodeMap.get(pathNode.parentId);
            if (parentNode && !parentNode.children.includes(pathNode)) {
                parentNode.children.push(pathNode);
                parentNode.children = parentNode.children.filter((e: any) => e.disabled != true).sort((a: any, b: any) => a.order - b.order);


            }
            pathNode = parentNode;
        }
    });

    // 找到新的根节点（即没有父节点或其父节点不在新树中的节点）
    const newRoots = Array.from(newNodeMap.values()).filter(
        (node) => node.parentId === "0" || !newNodeMap.has(node.parentId)
    );
    newRoots.sort((a: any, b: any) => a.order - b.order);
    // 如果有多个顶层节点，我们选择第一个作为新树的根节点，或者返回整个列表作为森林
    return newRoots.length === 1 ? newRoots[0] : newRoots;
}
export {
    buildSubtreeFromLeaves
}